<?php
class cmsdream_data extends cmsdream_cache {

	public function get_friend_site($name) {
		$db = $GLOBALS['DB'];
		$tb = $GLOBALS['C']->TABLE_PREFIX;
		$lk = $this->get("friend-site-$name", true);
		if(!$lk) {
			foreach($db->fetch_all("SELECT link_id AS id,link_url AS url,link_name AS name,link_image AS image,
							link_target AS target,link_description AS description,link_rss AS rss FROM {$tb}links WHERE link_id IN(
						SELECT object_id FROM {$tb}term_relationships WHERE term_taxonomy_id IN(
							SELECT term_taxonomy_id FROM {$tb}term_taxonomy WHERE term_id IN(
								SELECT term_id FROM {$tb}terms WHERE slug = '$name'
							)
						)
					) AND link_visible = 'Y' ORDER BY link_rating DESC,link_id ASC") as $key => $row) {
				$lk[$key] = new stdClass;
				$lk[$key] = $row;
				$lk[$key]->description = htmlspecialchars($row->description);
			}
			$this->write("friend-site-$name", str_replace("'", "\\'", serialize($lk)), time());
		}
		return $lk;
	}

	public function get_simple_posts_list($limit = 10, $order = "`post_date` DESC") {
		$db = $GLOBALS['DB'];
		$tb = $GLOBALS['C']->TABLE_PREFIX;
		$lp = $this->get("simple-posts-list-$limit");
		if(!$lp) {
			foreach($db->fetch_all("SELECT ID, post_title, post_date, comment_count FROM {$tb}posts 
						WHERE post_status = 'publish' AND post_type = 'post' ORDER BY $order LIMIT $limit") as $key => $row) {
				$lp[$key] = new stdClass;
				$lp[$key]->ID = $row->ID;
				$lp[$key]->title = htmlspecialchars($row->post_title);
				$lp[$key]->comment = $row->comment_count;
				$lp[$key]->date = $row->post_date;
				$lp[$key]->url = $this->url('post',$row->ID);
			}
			$this->write("simple-posts-list-$limit", str_replace("'", "\\'", serialize($lp)), (time() + $GLOBALS['C']->CACHETIME));
		}
		return $lp;
	}

	public function get_archive_by_date($limit = 30) {
		$db = $GLOBALS['DB'];
		$tb = $GLOBALS['C']->TABLE_PREFIX;
		$wd = $this->get("archive-by-date-$limit");
		if(!$wd) {
			foreach($db->fetch_all("SELECT `date`,title, COUNT(*) AS `count` FROM (
					SELECT ID, post_title AS title, SUBSTRING( `post_date` , 1, 7 ) AS `date`
					FROM {$tb}posts WHERE `post_type` = 'post' AND `post_status` = 'publish'
				) AS `P` GROUP BY `date` ORDER BY `date` DESC LIMIT $limit") as $key => $row) {
				$wd[$key] = new stdClass;
				$wd[$key]->date = $row->date;
				$wd[$key]->title = htmlspecialchars($row->title);
				$wd[$key]->count = $row->count;
				$wd[$key]->url = $this->url('date',$row->date);
			}
			$this->write("archive-by-date-$limit", str_replace("'", "\\'", serialize($wd)), (time() + $GLOBALS['C']->CACHETIME));
		}
		return $wd;
	}

	public function get_nav_menus($menu_name) {
		$db = $GLOBALS['DB'];
		$tb = $GLOBALS['C']->TABLE_PREFIX;
		$menu = $this->get("nav-menu-$menu_name", true);
		if(!$menu) {
			$sql = "SELECT m.meta_key,m.meta_value,m.post_id,p.post_title,p.post_excerpt FROM 
					{$tb}postmeta AS m LEFT JOIN {$tb}posts AS p ON p.ID = m.post_id WHERE m.post_id IN (
						SELECT object_id FROM {$tb}term_relationships WHERE term_taxonomy_id IN (
							SELECT term_taxonomy_id FROM {$tb}term_taxonomy WHERE term_id IN (
								SELECT term_id FROM {$tb}terms WHERE slug = '$menu_name'
							) AND taxonomy = 'nav_menu'
						)
					) ORDER BY p.menu_order ASC";

			$pm = array();
			foreach($db->fetch_all("$sql") as $row){
				$pm[$row->post_id][$row->meta_key] = $row->meta_value;
				$pm[$row->post_id]['title'] = $row->post_title;
				$pm[$row->post_id]['description'] = $row->post_excerpt;
			}
			$objId = array();
			foreach($pm as $key => $row) {
				$PID = $row['_menu_item_object_id'];
				if($row['_menu_item_object']!=='custom') {
					$objId[$row['_menu_item_object']][] = $PID;
				}
				$menu[$PID]['key'] = $key;
				$menu[$PID]['type'] = $row['_menu_item_object'];
				$menu[$PID]['title'] = $row['title'];
				$menu[$PID]['description'] = $row['description'];
				$menu[$PID]['url'] = $row['_menu_item_url'];
				$menu[$PID]['target'] = $row['_menu_item_target'];
				$menu[$PID]['parent'] = $row['_menu_item_menu_item_parent'];
				$menu[$PID]['children'] = null;
			}
			if(!empty($objId['page'])) {
				foreach($db->fetch_all("SELECT ID,post_title FROM {$tb}posts WHERE ID IN(".implode(',',$objId['page']).")") as $row){
					if(empty($menu[$row->ID]['title'])) $menu[$row->ID]['title'] = $row->post_title;
					$menu[$row->ID]['url'] = $this->url('page', $row->ID);
				}
			}
			if(!empty($objId['category'])) {
				foreach($db->fetch_all("SELECT term_id AS ID,`name` FROM {$tb}terms WHERE term_id IN(".implode(',',$objId['category']).")") as $row){
					if(empty($menu[$row->ID]['title'])) $menu[$row->ID]['title'] = $row->name;
					$menu[$row->ID]['url'] = $this->url('category', $row->ID);
				}
			}
			$menu = $this->_get_nav_menus_rebuild($menu);
			$this->write("nav-menu-$menu_name", str_replace("'", "\\'", serialize($menu)), time());
		}
		return $menu;
	}
	
	public function get_author_detail($aid = 0) {
		if(!$aid) return NULL;
		$author = $this->get("author-$aid", true);
		if(!$author) {
			$db = $GLOBALS['DB'];
			$tb = $GLOBALS['C']->TABLE_PREFIX;
			
			$fields = array("ID",
							"user_nicename AS nicename",
							"user_email AS email",
							"user_url AS url",
							"display_name"
						);
			$fields = implode(',',$fields);
			$author = $db->fetch("SELECT $fields FROM {$tb}users WHERE ID = $aid LIMIT 1");
			$author->display_name = htmlspecialchars($author->display_name);
			foreach($db->fetch_all("SELECT meta_key,meta_value FROM {$tb}usermeta WHERE user_id = $aid") AS $key => $row) {
				if(preg_match('/^([a-z])\:([\d]+)\:\{(.*)\}$/i', $row->meta_value) || preg_match('/^([a-z])\:([\d]+)\:"stdClass"\:([\d]+)\:\{(.*)\}$/i', $row->meta_value)) {
					$author->{$row->meta_key} = unserialize($row->meta_value);
				} else {
					$author->{$row->meta_key} = htmlspecialchars($row->meta_value);
				}
			}
			$this->write("author-$aid", str_replace("'", "\\'", serialize($author)), time());
		}
		return($author);
	}
	
	//这部分非常困难，先固定死，以后再说
	public function url($c, $key, $reqs = null) {
		$ext = '';
		if(!empty($reqs)) {
			if(is_array($reqs)) {
				$q = array();
				foreach($reqs as $k => $value) {
					$q[] = "$k=$value";
				}
				$ext = implode('&', $q);
			} else {
				$ext = (string) $reqs;
			}
			$ext = '?' . $ext;
		}
		//attachment,nav_menu_item,page,post,revision
		if(!empty($this->Data['_links']) && isset($this->Data['_links'][$c][$key])) {
			return ($GLOBALS['C']->ABSURL ? $GLOBALS['S']->home : $GLOBALS['C']->SITEPATH) . $this->Data['_links'][$c][$key] . $ext;
		}
		
		$setting = $this->get('setting', true);
		$link = '';
		if($c=='date') {
			if(!empty($setting->rewrite_rules)) {
				$link = str_replace("%post_id%", "date/" . date("Y/m", strtotime($key)), $setting->permalink_structure);
			} else {
				$link = "/?m=" . date("Ym", strtotime($key));
			}
		}
		if($c=='page') {			
			if ('page' == $setting->show_on_front && $key == $setting->show_on_front) {
				$link = "/";
			} else {
				if(!empty($setting->rewrite_rules)) {
					$link = $this->get_page_uri($key);
				} else {
					$link = "/?page_id=$key";
				}
			}
		}
		if($c=='category') {
			if(!empty($setting->rewrite_rules)) {
				$link = $setting->category_base . $this->get_category_uri($key);
			} else {
				$link = "/?cat=$key";
			}
		}
		if($c=='post_tag') {
			if(!empty($setting->rewrite_rules)) {
				$link = $setting->tag_base . "/" . $this->get_tag_uri($key);
			} else {
				$link = "/?tag=$key";
			}
		}
		if($c=='author') {
			if(!empty($setting->rewrite_rules)) {
				$link = str_replace("%post_id%", "author/$key", $setting->permalink_structure);
			} else {
				$link = "/?author=$key";
			}
		}
		if($c=='post' || $c=='attachment') {
			if(!empty($setting->rewrite_rules)) {
				$link = str_replace("%post_id%", $this->get_post_uri($key), $setting->permalink_structure);
			} else {
				$link = "/?p=$key";
			}
		}
		if(!isset($this->Data['_links'][$c])) $this->Data['_links'][$c] = array();
		if(!isset($this->Data['_links'][$c][$key])) $this->Data['_links'][$c][$key] = array();
		$this->Data['_links'][$c][$key] = $link;
		$this->write("_links", str_replace("'", "\\'", serialize($this->Data['_links'])), time());
		return ($GLOBALS['C']->ABSURL ? $GLOBALS['S']->home : $GLOBALS['C']->SITEPATH) . $link . $ext;
	}
	
	public function get_term_by_name($name) {
		$arr = $this->get("term-by-name-$name");
		if(!$arr) {
			$arr = $this->get_terms($name);
			$this->write("term-by-name-$name", str_replace("'", "\\'", serialize($arr)), (time() + $GLOBALS['C']->CACHETIME));
		}
		return $arr;
	}
	
	public function get_term_by_id($ID, $c = 'category') {
		if($ID==0) return NULL;
		
		if(!empty($this->Data['_terms']) && isset($this->Data['_terms'][$ID][$c])) {
			return $this->Data['_terms'][$ID][$c];
		}
		$db = $GLOBALS['DB'];
		$tb = $GLOBALS['C']->TABLE_PREFIX;
		$TC = array();
		foreach($db->fetch_all("SELECT t.ID,t.name,x.taxonomy FROM (SELECT term_id AS ID,name FROM {$tb}terms WHERE term_id IN (
					SELECT term_id FROM {$tb}term_taxonomy WHERE term_taxonomy_id IN (
						SELECT term_taxonomy_id FROM {$tb}term_relationships WHERE object_id IN (
							SELECT ID FROM {$tb}posts WHERE ID = $ID
						)
					))) AS t LEFT JOIN {$tb}term_taxonomy AS x ON x.term_id = t.ID") as $key => $row) {
			$TC[$row->taxonomy][$key] = $row;
		}
		if(!isset($this->Data['_terms'][$ID])) $this->Data['_terms'][$ID] = array();
		$this->Data['_terms'][$ID] = $TC;
		if(!isset($this->Data['_terms'][$ID][$c])) $this->Data['_terms'][$ID][$c] = array();
		$this->write("_terms", str_replace("'", "\\'", serialize($this->Data['_terms'])), time());
		return isset($this->Data['_terms'][$ID][$c]) ? $this->Data['_terms'][$ID][$c] : NULL;
	}

	public function __construct() {
		$this->Data['_links'] = $this->get("_links", true);
		$this->Data['_terms'] = $this->get("_terms", true);
	}
	
	public function __destruct(){
	
	}
	
}

